<template>
  <div>
    <div class="switch-box">
        <div class="switch-wrap">
          <div
            class="switch-item"
            :class="{'switch-item-on': selectTab == index}"
            @click.stop="changeTabs(item, index)"
            v-for="(item, index) in dragramTypeList"
            :key="item.lgid + index"
          >
              <span v-lang="{lang: controlSto.language, lgid: item.lgid}">{{ item.tname }}</span>
          </div>
        </div>
      </div>
      <!-- <uiEchart :config="optionBar" ref="chart" :vt="echartoptVt"></uiEchart> -->
      <div ref="chartVolcano" class="chart-box-three" v-show="!vLoading && (volcanoDataDown.length || volcanoDataNotSignificant.length || volcanoDataUp.length) && selectTab == 0"></div>
      <div ref="chartScatter" class="chart-box-three" v-show="!sLoading && (dataScatter1.length || dataScatter2.length || dataScatter3.length) && selectTab == 1"></div>
      <div ref="chartBar" class="chart-box-three" v-show="!bLoading && dataBar.length && selectTab == 2"></div>
      <div class="no-data-box" v-show="vLoading && selectTab == 0">
        <img :src="Loading"/>
        <div class="no-data-txt" v-lang="{lang: controlSto.language, lgid: '-131'}">loading...</div>
      </div>
      <div class="no-data-box" v-show="sLoading && selectTab == 1">
        <img :src="Loading"/>
        <div class="no-data-txt" v-lang="{lang: controlSto.language, lgid: '-131'}">loading...</div>
      </div>
      <div class="no-data-box" v-show="bLoading && selectTab == 2">
        <img :src="Loading"/>
        <div class="no-data-txt" v-lang="{lang: controlSto.language, lgid: '-131'}">loading...</div>
      </div>
      <div
        class="no-data-box"
        v-if="selectTab == 0"
        v-show="
          (!vLoading && (!volcanoDataDown.length && !volcanoDataNotSignificant.length && !volcanoDataUp.length))
        "
      >
        <img :src="NodtaPng"/>
        <div class="no-data-txt" v-lang="{lang: controlSto.language, lgid: '-118'}">暂无数据</div>
      </div>
      <div
        class="no-data-box"
        v-if="selectTab == 1"
        v-show="
          (!sLoading && (!dataScatter1.length && !dataScatter2.length && !dataScatter3.length))
        "
      >
        <img :src="NodtaPng"/>
        <div class="no-data-txt" v-lang="{lang: controlSto.language, lgid: '-118'}">暂无数据</div>
      </div>
      <div
        class="no-data-box"
        v-if="selectTab == 2"
        v-show="
          !bLoading && !dataBar.length
        "
      >
        <img :src="NodtaPng"/>
        <div class="no-data-txt" v-lang="{lang: controlSto.language, lgid: '-118'}">暂无数据</div>
      </div>
  </div>
</template>
<script setup>
import { ref, toRefs, computed, onMounted, watch} from 'vue'
import { controlStore } from '@/stores/control'
import uiEchart from '@/components/ui-echart.vue' 
import * as echarts from "echarts";
import Loading from '@/assets/img/loading.gif'
import NodtaPng from '@/assets/img/noData.png'
const props = defineProps({
  dataBar: {
    type: Array,
    default: () => []
  },
  volcanoDataDown: {
    type: Array,
    default: () => []
  },
  volcanoDataNotSignificant: {
    type: Array,
    default: () => []
  },
  volcanoDataUp: {
    type: Array,
    default: () => []
  },
  dataScatter1: {
    type: Array,
    default: () => []
  },
  dataScatter2: {
    type: Array,
    default: () => []
  },
  dataScatter3: {
    type: Array,
    default: () => []
  },
  vLoading: {
    type: Boolean,
    default: false
  },
  sLoading: {
    type: Boolean,
    default: false
  },
  bLoading: {
    type: Boolean,
    default: false
  }
})
const controlSto = controlStore();
const selectTab = ref(0);
const { dataBar, volcanoDataDown, volcanoDataNotSignificant, volcanoDataUp, dataScatter1, dataScatter2, dataScatter3, vLoading, bLoading } = toRefs(props)
const echartoptVt = new Date().valueOf(); 
const chartVolcano = ref(null);
const chartScatter = ref(null);
const chartBar = ref(null);
let chartDomVolcano = null;
let chartDomScatter = null;
let chartDomBar = null;
const dragramTypeList = [
		{
			tname: 'Differential expressed genes',
			lgid: '-120',
			code: 'Differential expressed genes'
		}, {
			tname: 'Gene Ontology analysis',
			lgid: '-121',
			code: 'Gene Ontology analysis'
		}, {
			tname: 'KEGG pathways',
			lgid: '-123',
			code: 'KEGG pathways'
		}
	]
const changeTabs = (item, index) => {
  selectTab.value = index;
  // if (index == 1) {
  //   initEchartScatter();
  // } else if (index == 2) {
  //   initEchartBar();
  // } else if(index == 0){
  //   initEchartVolcano();
  // }
}


// 柱状图option
const optionBar = computed(() => {
  const option = {
            dataset: {
                source: dataBar.value
            },
            dataZoom: [
                {
                    yAxisIndex: 0,
                    handleIcon: "circle",
                    handleSize: "70%",
                }
            ],
            title: {
                text: "SHVSM kegg_passway. enrichment",
                left: "center",
                top: "0%",
                textStyle: {
                    fontSize: 15
                },
                show: true
            },
            tooltip: {
                position: 'top'
            },
            grid: { containLabel: true },
            xAxis: {
                name: 'Count',
                nameLocation: "center",
                nameGap: 25,
                nameTextStyle: {
                    fontSize: 12,
                    fontWeight: "bold"
                },
            },
            yAxis: {
                type: 'category',
                axisLabel: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                name: 'Go ontology',
                nameLocation: 'end',
                nameGap: 5,
                nameTextStyle: {
                    fontSize: 12,
                    fontWeight: "bold"
                },
            },
            visualMap: {
                orient: 'horizontal',
                left: 'center',
                min: 2.82e-15,                  //需要跟随所有数据的第一列的最小值变化
                max: 0.994625688,                //需要跟随所有数据的第一列的最大值变化
                calculable: true,
                text: ['p.adjust'],
                dimension: 0,
                precision: 3,
                inRange: {
                    color: ['#FD665F', '#FFCE34', '#65B581']
                }
            },
            series: [
                {
                    type: 'bar',
                    encode: {
                        x: 'Count',
                        y: 'Description'
                    }
                }
            ]
        };
        return option
}) 

const initEchartBar = (() => {
  chartDomBar = echarts.init(chartBar.value, optionBar.value);
  chartDomBar.setOption(optionBar.value);
})

//火山图
const optionVolcano = computed(() => {
  //坐标轴名称，不需要变化
  const schema = [
      { name: 'log2FoldChange', index: 0, text: 'log2FoldChange' },
      { name: '-log10(p-value)', index: 1, text: '-log10(p-value)' }
    ];
    //一些图的样式，不变
    const itemStyle = {
      opacity: 0.8,
      shadowBlur: 10,
      shadowOffsetX: 0,
      shadowOffsetY: 0,
      shadowColor: 'rgba(0,0,0,0.3)'
    };
  const option = {
      color: ['blue', 'grey', 'red'],
      emphasis: {
        focus: 'series',
        blurScope: 'coordinateSystem'
      },
      legend: {
        top: '5%',
        left: 'right',
        data: ['Down', 'Not significant', 'Up'],
        textStyle: {
          fontSize: 16
        }
      },
      grid: {
        left: '10%',
        right: 150,
        top: '18%',
        bottom: '10%'
      },
      tooltip: {
        backgroundColor: 'rgba(255,255,255,0.7)',
        formatter: function (param) {
          var value = param.value;
          // prettier-ignore
          return '<div style="text-align: left;border-bottom: 1px solid rgba(255,255,255,.3); font-size: 18px;padding-bottom: 7px;margin-bottom: 7px">'
            + param.seriesName + '--' + value[2]
            + '</div>'
            + '<div  style="text-align: left;">'+ schema[0].text + ':' + value[0] +'</div>'
            + '<div  style="text-align: left;">' + schema[1].text + ':' + value[1] + '</div>'
        }
      },
      xAxis: {
        type: 'value',
        name: 'log2FoldChange',
        nameGap: 16,
        nameTextStyle: {
          fontSize: 16
        },
        splitLine: {
          show: false
        }
      },
      yAxis: {
        axisLine: {
          onZero: false
        },
        type: 'value',
        name: '-log10(p-value)',
        nameLocation: 'end',
        nameGap: 20,
        nameTextStyle: {
          fontSize: 16
        },
        splitLine: {
          show: false
        }
      },

      //需要改变min和max的值
      visualMap: [
        {
          left: 'right',
          top: '13%',
          dimension: 1,
          min: 0,                           //需要跟随所有数据的第二列的最小值变化（取整数）
          max: 188,                         //需要跟随所有数据的第二列的最大值变化（取整数）
          itemWidth: 30,
          itemHeight: '200%',
          calculable: true,
          precision: 0,
          text: ['-log10(p-value)'],
          textGap: 30,
          inRange: {
            symbolSize: [5, 30]
          },
          outOfRange: {
            symbolSize: [5, 30],
            color: ['rgba(255,255,255,0.4)']
          },
          controller: {
            inRange: {
              color: ['orange']
            },
            outOfRange: {
              color: ['#999']
            }
          }
        }
      ],
      //下面的不需要改变，data对应上面的不同的数据
      series: [
        {
          name: 'Down',
          type: 'scatter',
          itemStyle: itemStyle,
          data: volcanoDataDown.value
        },
        {
          name: 'Not significant',
          type: 'scatter',
          itemStyle: itemStyle,
          data: volcanoDataNotSignificant.value
        },
        {
          name: 'Up',
          type: 'scatter',
          itemStyle: itemStyle,
          data: volcanoDataUp.value
        }
      ]
    };
    return option;
})
const initEchartVolcano = (() => {
  chartDomVolcano = echarts.init(chartVolcano.value, optionVolcano.value);
  chartDomVolcano.setOption(optionVolcano.value);
})

//散点图
const optionScatter = computed(() => {
  const schema = [
      { name: 'GeneRatio', index: 0, text: 'GeneRatio' },
      { name: 'name', index: 1, text: 'name' },
      { name: 'Count', index: 2, text: 'Count' },
      { name: 'p.adjust', index: 3, text: 'p.adjust' },
    ];
    const itemStyle = {
      opacity: 0.8,
      shadowBlur: 10,
      shadowOffsetX: 0,
      shadowOffsetY: 0,
      shadowColor: 'rgba(0,0,0,0.3)'
    };
  const option = {
      legend: {
        top: '4%',
        itemStyle: {
          color: "white",
          borderColor: "black",
          borderWidth: 1

        },
        data: ['BP', 'CC', 'MF'],
        textStyle: {
          fontSize: 16
        }
      },
      title: {
        text: "Gene Ontology analysis",
        left: "center",
        top: "-1%",
        textStyle: {
          fontSize: 15
        },
        show: true
      },
      grid: {
        left: '10%',
        right: '10%',
        top: '12%',
        bottom: '18%'
      },
      tooltip: {
        backgroundColor: 'rgba(255,255,255,0.7)',
        formatter: function (param) {
          var value = param.value;
          return `<div style="text-align:left;border-bottom: 1px solid rgba(255,255,255,.3); font-size: 18px;padding-bottom: 7px;margin-bottom: 7px">`
            + schema[1].text + ': ' + value[1] + `<br>`
            + schema[0].text + ': ' + value[0] + `<br>`
            + schema[2].text + ': ' + value[2] + `<br>`
            + schema[3].text + ': ' + value[3] + `<br>`
            + '</div>'
        }
      },
      xAxis: {
        type: 'value',
        name: 'GeneRatio',
        nameLocation: "center",
        nameGap: 25,
        nameTextStyle: {
          fontSize: 12,
          fontWeight: "bold"
        },
      },
      yAxis: {
        type: 'category',
        axisLabel: {
          show: false
        },
        axisTick: {
          show: false
        },
        name: 'Pathways',
        nameLocation: 'end',
        nameGap: 5,
        nameTextStyle: {
          fontSize: 12,
          fontWeight: "bold"
        },
      },
      emphasis: {
        focus: 'series',
        blurScope: 'coordinateSystem'
      },
      dataZoom: [
        {
          yAxisIndex: 0,
          handleIcon: "circle",
          handleSize: "70%",
        }
      ],
      visualMap: [
        {
          orient: 'horizontal',
          left: '60%',
          bottom: 0,
          dimension: 2,
          min: 4,               //需要跟随所有数据的第三列的最小值变化（取整数）
          max: 49,              //需要跟随所有数据的第三列的最大值变化（取整数）
          calculable: true,
          precision: 0,
          text: ['Count'],
          textGap: 30,
          inRange: {
            symbolSize: [10, 50]
          },
          outOfRange: {
            symbolSize: [10, 50],
            opacity: 0.1
          },
          controller: {
            inRange: {
              color: ['orange']
            },
            outOfRange: {
              color: ['#999']
            }
          }
        },
        {
          orient: 'horizontal',
          left: '20%',
          bottom: '0',
          dimension: 3,
          min:  1.85e-14,                //需要跟随所有数据的第四列的最小值变化
          max: 0.009361377,             //需要跟随所有数据的第四列的最大值变化
          precision: 3,
          calculable: true,
          text: ['p.adjust'],
          textGap: 30,
          inRange: {
            color: ['#FD665F', '#FFCE34', '#65B581']
          },
          outOfRange: {
            color: ['rgba(255,255,255,0.4)']
          },
          controller: {
            outOfRange: {
              color: ['#999']
            }
          }
        }
      ],
      series: [
        {
          name: 'BP',
          type: 'scatter',
          itemStyle: itemStyle,
          symbol: 'rect',
          data: dataScatter1.value
        },
        {
          name: 'CC',
          type: 'scatter',
          itemStyle: itemStyle,
          symbol: 'triangle',
          data: dataScatter2.value
        },
        {
          name: 'MF',
          type: 'scatter',
          itemStyle: itemStyle,
          symbol: 'circle',
          data: dataScatter3.value
        }
      ]
    };
    return option;
})

const initEchartScatter = (() => {
  chartDomScatter = echarts.init(chartScatter.value, optionScatter.value);
  chartDomScatter.setOption(optionScatter.value);
})
defineExpose({
  initEchartVolcano,
  initEchartScatter,
  initEchartBar
})
onMounted(()=> {
  initEchartBar();
  initEchartVolcano();
  initEchartScatter();
})
watch(() => [volcanoDataDown, volcanoDataNotSignificant, volcanoDataUp],(n, v) => {
  if (n != v) {
    optionVolcano.value.series[0].data = n[0].value
    optionVolcano.value.series[1].data = n[1].value
    optionVolcano.value.series[2].data = n[2].value
    initEchartVolcano()
  }
}, { deep: true})
watch(() => [dataScatter1, dataScatter2, dataScatter3],(n, v) => {
  if (n != v) {
    optionScatter.value.series[0].data = n[0].value
    optionScatter.value.series[1].data = n[1].value
    optionScatter.value.series[2].data = n[2].value
    initEchartScatter();
  }
}, { deep: true})
watch(() => [dataBar],(n, v) => {
  if (n != v) {
    optionBar.value.dataset.source = n[0].value
    initEchartBar();
  }
}, { deep: true})
</script>
<style scoped lang="scss">
.switch-box {
  padding-bottom: 32px;
  text-align: center;
  .switch-wrap {
    display: inline-block;
    border: 1px solid #BC9F77;
    border-radius: 30px;
    font-size: 0;
    color: #967846;
    .switch-item {
      display: inline-block;
      height: 40px;
      // width: 200px;
      padding: 0 32px;
      line-height: 40px;
      border-right: 1px solid #BC9F77;
      font-weight: 600;
      font-size: 18px;
      cursor: pointer;
      &:first-child {
        border-top-left-radius: 16px;
        border-bottom-left-radius: 16px;
      }
      &:last-child {
        border-right: none;
        border-top-right-radius: 16px;
        border-bottom-right-radius: 16px;
      }
      &.switch-item-on {
        color: #fff;
        background-color: #BC9F77;
      }
    }
  }
  .chart-box-three {
    // width: 100%;
    height: 400px;
    display: block;
    // div:first-child {
    //   width: 100%;
    // }
    :deep(){
      canvas {
        // width: 100%;
        height: 400px;
      }
    }
  }
}
.no-data-box {
    width: 100%;
    height: 264px;
    text-align: center;
    position: relative;
    img {
        margin-top: 20px;
    }
    .no-data-txt {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 14px;
        color: #BC9F77;
        line-height: 20px;
        text-align: center;
        font-style: normal;
        position: absolute;
        width: 100%;
        bottom: 60px;
    }
}
</style>